'''
Author: admin@attacker.club
Date: 2022-09-20 17:37:29
LastEditTime: 2022-09-21 16:54:04
Description: 
pip install aliyun-python-sdk-domain==3.14.9
pip install aliyun-python-sdk-alidns==3.0.0
pip install xlwt xlrd xlutils pythonping 
'''
#!/usr/bin/env python
#coding=utf-8
import sys
import json
import re
import socket
from turtle import st
from pythonping import ping
import xlwt
import xlrd
from xlutils.copy import copy


from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcore.auth.credentials import AccessKeyCredential
from aliyunsdkcore.auth.credentials import StsTokenCredential
from aliyunsdkdomain.request.v20180129.QueryAdvancedDomainListRequest import QueryAdvancedDomainListRequest
from aliyunsdkalidns.request.v20150109.DescribeDomainRecordsRequest import DescribeDomainRecordsRequest

def QueryAdvancedDomainList():
    request = QueryAdvancedDomainListRequest()
    request.set_accept_format('json')
    request.set_PageNum(1)
    request.set_PageSize(10)
    response = client.do_action_with_exception(request)
    ret = json.loads(response.decode("UTF-8"))
    return ret['Data']['Domain']

def DescribeDomainRecords(domain):
    next = 0
    request = DescribeDomainRecordsRequest()
    request.set_accept_format('json')
    # request.set_PageNumber(1) # 当前页数
    request.set_PageSize(500) #  页查询时设置的每页行数
    request.set_DomainName(domain)
    
    Records = []
    for i in range(1, 100): 
        request.set_PageNumber(i) #当前分页数
        response = client.do_action_with_exception(request)
        result = json.loads(response.decode("UTF-8"))
        record = result['DomainRecords']['Record']
        for i in (record):
            Records.append(i)
        if len(record) <1 : # 如果没有记录，结束循环页数
            break
    return Records


# 写入表格
def write_excel_xls(path, sheet_name, value):
    index = len(value)  # 获取需要写入数据的行数
    workbook = xlwt.Workbook()  # 新建一个工作簿
    sheet = workbook.add_sheet(sheet_name)  # 在工作簿中新建一个表格
    for i in range(0, index):
        for j in range(0, len(value[i])):
            sheet.write(i, j, value[i][j])  # 像表格中写入数据（对应的行和列）
    workbook.save(path)  # 保存工作簿
    # logger.info("xls格式表格数据写入!")

# 写入数据
def write_excel_xls_append(path, value):
    index = len(value)  # 获取需要写入数据的行数
    workbook = xlrd.open_workbook(path)  # 打开工作簿
    sheets = workbook.sheet_names()  # 获取工作簿中的所有表格
    worksheet = workbook.sheet_by_name(sheets[0])  # 获取工作簿中所有表格中的的第一个表格
    rows_old = worksheet.nrows  # 获取表格中已存在的数据的行数
    new_workbook = copy(workbook)  # 将xlrd对象拷贝转化为xlwt对象
    new_worksheet = new_workbook.get_sheet(0)  # 获取转化后工作簿中的第一个表格
    for i in range(0, index):
        for j in range(0, len(value[i])):
            new_worksheet.write(i + rows_old, j, value[i][j])  # 追加写入数据，注意是从i+rows_old行开始写入
    new_workbook.save(path)  # 保存工作簿
    print("xls格式表格数据更新完毕")


if __name__ == "__main__":
    id =  sys.argv[1]
    secret = sys.argv[2]
    credentials = AccessKeyCredential(id, secret)
    client = AcsClient(region_id='cn-shanghai', credential=credentials)

    full_content = []
    Domians = QueryAdvancedDomainList()
    for i in Domians:
        print("="*10)
        domian = i['DomainName']
        Org = i['ZhRegistrantOrganization']
        
        print(f"{Org} {domian}")
        DomainRecords = DescribeDomainRecords(domian)
        # for i in DomainRecords:
        #     print("{}.{}".format(i['RR'],i['DomainName']))     
        for i in DomainRecords:
            row_list = []
            if i['Type'] == 'A' or  i['Type'] == 'CNAME':
                host = "{}.{}".format(i['RR'],i['DomainName'])
                host = re.sub('@.','',host) # 去掉主机@
                address = i['Value'] # A,CNAME 记录
                row_list.append(host)
                row_list.append(address)
                
                if  i['Type'] == 'CNAME':
                    try:
                        # print("domian:",domian,address)
                        addrs  = socket.getaddrinfo(host, None)
                        ip = addrs[1][4][0]
                        ping_result = ping(ip)
                    except Exception as e:
                        print(f"{host} 域名解析失败!" )
                        status = '域名解析失败!'
                        row_list.append(status)
                        full_content.append(row_list)
                        continue # 跳过本次循环
                else:
                    try:
                        ping_result = ping(address)
                    except Exception as e:
                        print(f"{host} ping异常!  {e}")
                        status = f"ping异常!  {e}"
                        row_list.append(status)
                        full_content.append(row_list)
                        continue # 跳过本次循环

                if "Reply" in str(ping_result):
                    print("{0} 解析到 {1} 检查ok".format(host,address))
                    status = "ok"
                    row_list.append(status)
                else:
                    print("{0} 解析到 {1} ping不可达".format(host,address))
                    status = "ping不可达"
                    row_list.append(status)
                full_content.append(row_list)
                    

    ## 将数据列表写入表格 
    """
    [
     ["pre-1.huligou.com","47.103.1.1", "ok"],  
     ["pre-123.huligou.com","47.103.1.122", "ping不可达"],
     ["pre-111.huligou.com","47.103.1.123", "No route to host"],
     ["cdn.huligou.com","cdn.xxx.com.w.kunluncan.com", "ok"],
    ]
    """
    book_name_xls = f'域名.xls'
    sheet_name_xls = f'默认'
    value_title = [["域名", "解析地址", "ping检测状态"], ]
    write_excel_xls(book_name_xls, sheet_name_xls, value_title)
    write_excel_xls_append(book_name_xls, full_content)
                
                
        

 
        
    




          
            
    
    



    
    